//
// Created by 崔世强 on 2018/2/2.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import SwiftHash

class FileDownloadTool {
    static let instance = FileDownloadTool()
    private init(){}
    
    
    func download(_ from:URL,to:URL,onFinish: ((_ filePath:String) throws -> ())? = nil,onError: ((_ error:Error)-> Void)? = nil){
        let url = from
        let request = URLRequest(url: url)
        let session = URLSession.shared
        let downloadTask = session.downloadTask(with: request,completionHandler: { (location:URL?, response:URLResponse?, error:Error?) -> Void in
            if let err = error {
                onError?(err)
                return
            }
            
            do {
                //输出下载文件原来的存放目录
                print("location:\(location)")
                //location位置转换
                let locationPath = location!.path
                let toLocationPath = to.path
                //创建文件管理器
                let fileManager = FileManager.default
                
                //创建目标地址中任何不存在的文件夹
                if let end = toLocationPath.lastIndex(of: "/") {
                    let dir = String(toLocationPath[toLocationPath.startIndex..<end])
                    try fileManager.createDirectory(atPath: dir, withIntermediateDirectories: true, attributes: nil)
                }
                
//                try fileManager.moveItem(atPath: locationPath, toPath: toLocationPath)
                try Cipher.shared.decryptFile(atPath: locationPath, toDecryptedPath: toLocationPath)
                print("new location:\(toLocationPath)")
                try onFinish?(toLocationPath)
            } catch {
                onError?(error)
            }
        })
        downloadTask.resume()
    }

    func download(_ fileName:String,onFinish: @escaping (_ filePath:String) throws -> (),onError: @escaping (_ error:Error)-> Void){
        let url = URL(string: "\(IM_HTTP_SERVER_URL_STRING)im/file/download/audios/\(fileName)")
        let request = URLRequest(url: url!)
        let session = URLSession.shared
        let downloadTask = session.downloadTask(with: request,completionHandler: { (location:URL?, response:URLResponse?, error:Error?) -> Void in
            if let err = error {
                onError(err)
                return
            }

            do {
                //输出下载文件原来的存放目录
                print("location:\(location)")
                //location位置转换
                let locationPath = location!.path
                //拷贝到用户目录
                let audioDir = AppStatusManager.instance.urlForUser!.appendingPathComponent("audio",isDirectory: true)
              try FileManager.default.createDirectory(at: audioDir, withIntermediateDirectories: true, attributes: nil)
                let documents:String = AppStatusManager.instance.urlForUser!.appendingPathComponent("audio",isDirectory: true)
                        .appendingPathComponent("\(fileName).amr",isDirectory: false).path
                //创建文件管理器
//                let fileManager = FileManager.default
//                try fileManager.moveItem(atPath: locationPath, toPath: documents)
                try Cipher.shared.decryptFile(atPath: locationPath, toDecryptedPath: documents)
                print("new location:\(documents)")
                try onFinish(documents)
            } catch {
                onError(error)
            }
        })
        downloadTask.resume()
    }

    func existsUserAvatar(_ userId:Int) -> Bool {
        let fileName = MD5("\(userId)").uppercased()
        let path = AppStatusManager.instance.urlForUserAvatar?.appendingPathComponent("\(fileName).png",isDirectory: false).path ?? ""
        if FileManager.default.fileExists(atPath: path) {
            return true
        }
        return false
    }

    func syncUserAvatar(_ userId:Int,syncSuccess: @escaping (_ filePath:String) -> Void) {
        if userId == 0 {
            return
        }
        if existsUserAvatar(userId) {
            return
        }


        let urlPath: String = "\(AppStatusManager.instance.rnServer)users/userInfo?id=\(userId ?? 0)"
        let url = URL(string: urlPath)!
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        let queue = OperationQueue()

        NSURLConnection.sendAsynchronousRequest(request, queue: queue) { response, data, error in
            if let respData = data {
                if let jsonResult = try? JSONSerialization.jsonObject(with: respData, options: []) as? NSDictionary {
                    if (jsonResult?["status"] as? Bool ?? false) {
                        if let data = jsonResult?["data"] as? Dictionary<String, Any> {
                            if let avatar = data["avatar"] as? String {
                                self.downloadAvatar(avatar,fileName:  MD5("\(userId)").uppercased(),onFinish: { (path) in
                                    syncSuccess(path)
                                })
                            }
                        }
                    }
                }
            }
        }
    }

    private func downloadAvatar(_ avatar:String,fileName:String,onFinish: @escaping (_ filePath:String) throws -> ()){
        let url = URL(string: "waim-resource.oss-cn-beijing.aliyuncs.com/\(avatar)")
        let request = URLRequest(url: url!)
        let session = URLSession.shared
        let downloadTask = session.downloadTask(with: request,completionHandler: { (location:URL?, response:URLResponse?, error:Error?) -> Void in
            if error != nil {
//                onError(err)
                return
            }

            do {
                //输出下载文件原来的存放目录
                print("avatar download location:\(location)")
                //location位置转换
                let locationPath = location!.path
                //拷贝到用户目录
                if let avatarDir = AppStatusManager.instance.urlForUserAvatar {
                    try FileManager.default.createDirectory(at: avatarDir , withIntermediateDirectories: true, attributes: nil)
                    let documents:String = avatarDir.appendingPathComponent("\(fileName).png",isDirectory: false).path
                    //创建文件管理器
                    let fileManager = FileManager.default
                    try fileManager.moveItem(atPath: locationPath, toPath: documents)
                    print(" avatar download new location:\(documents)")
                    try onFinish(documents)
                }

            } catch {
//                onError(error)
            }
        })
        downloadTask.resume()
    }
  
  
  
  func downloadSensitiveFile(onFinish: @escaping (_ filePath:String) throws -> ()){
    let url = URL(string: "waim-resource.oss-cn-beijing.aliyuncs.com/im/sensitive/\(sensitiveFileName)")
    let request = URLRequest(url: url!)
    let session = URLSession.shared
    let downloadTask = session.downloadTask(with: request,completionHandler: { (location:URL?, response:URLResponse?, error:Error?) -> Void in
      if error != nil {
        //                onError(err)
        return
      }
      do {
        //location位置转换
        let locationPath = location!.path
        //拷贝到用户目录
        if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
          let file = dir.appendingPathComponent(sensitiveFileName,isDirectory: false)
          let filePath = file.path
          //创建文件管理器
          let fileManager = FileManager.default
          if fileManager.fileExists(atPath: filePath) {
            _ = try fileManager.replaceItemAt(file, withItemAt: location!)
          } else {
            try fileManager.moveItem(atPath: locationPath, toPath: filePath)
          }
          print(" \(sensitiveFileName) downloaded new location:\(filePath)")
          try onFinish(filePath)
        }
        
      } catch {
        print("敏感词库更新异常：\(error)")
        //                onError(error)
      }
    })
    downloadTask.resume()
  }

}
